package com.five.calendar.ui.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.solver.Goal;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.five.calendar.ApplicationHelper;
import com.five.calendar.R;
import com.five.calendar.alarmmanager.clock.AlarmManagerUtil;
import com.five.calendar.common.observer.Observer;
import com.five.calendar.database.bean.TargetBean;
import com.five.calendar.database.bean.TargetDayBean;
import com.five.calendar.database.observer.TargetDayObservable;
import com.five.calendar.database.observer.TargetObservable;
import com.five.calendar.ui.widget.picktime.DatePickDialogHelper;
import com.five.calendar.ui.widget.picktime.OnSureLisener;
import com.five.calendar.utils.TimeUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by xin on 2017/9/3.
 */

public class GoalDetailAddActivity extends Activity implements View.OnClickListener {
    @BindView(R.id.target_name)
    EditText mTargetName;
    @BindView(R.id.start_time)
    RelativeLayout mStartTimeView;
    @BindView(R.id.start_time_show)
    TextView mStartTimeShow;
    @BindView(R.id.schedule_end_time)
    RelativeLayout mEndTimeView;
    @BindView(R.id.schedule_end_time_show)
    TextView mEndTimeShow;
    @BindView(R.id.alert_time)
    RelativeLayout mAlertTimeView;
    @BindView(R.id.alert_time_show)
    TextView mAlertTimeShow;
    @BindView(R.id.close)
    ImageView mCloseIcon;
    @BindView(R.id.color_1)
    ImageView mColor1;
    @BindView(R.id.color_2)
    ImageView mColor2;
    @BindView(R.id.color_3)
    ImageView mColor3;
    @BindView(R.id.color_4)
    ImageView mColor4;
    @BindView(R.id.color_5)
    ImageView mColor5;
    @BindView(R.id.color_6)
    ImageView mColor6;
    @BindView(R.id.color_center)
    ImageView mColorCenter;
    @BindView(R.id.save_goal)
    TextView mSaveGoal;
    @BindView(R.id.goal_note)
    EditText mNoteView;
    private Date mStartTime;
    private Date mEndTime;
    private Date mAlertTime;
    private long mStartTimeData;
    private long mEndTimeData;
    private long mAlertTimeData;
    private long mOriginalStartTimeData;
    private long mOriginalEndTimeData;
    private String mTitle;
    private String mNote;
    private String mAlertTimeText = "no reminder";
    private int mColor = 1;
    private String mType;
    private TargetBean mTargetBean;
    private boolean isCreate = true;
    private int[] mResourceId = new int[]{R.drawable.circle_shape_1, R.drawable.circle_shape_2, R.drawable.circle_shape_3, R.drawable.circle_shape_4, R.drawable.circle_shape_5, R.drawable.circle_shape_6};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goal_detail_add);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        Intent intent = getIntent();
        mType = intent.getStringExtra("type");
        initView();
        initEditData();
    }

    private void initEditData() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if(bundle != null && bundle.getSerializable("targetbean") != null){
            isCreate = false;
            mTargetBean = (TargetBean) bundle.getSerializable("targetbean");
            mStartTime = new Date(mTargetBean.startTime);
            mStartTimeData = mTargetBean.startTime;
            mOriginalStartTimeData = mTargetBean.startTime;
            String startTime = TimeUtils.timeFormatString(mStartTime);
            mStartTimeShow.setText(startTime);
            mEndTimeData = mTargetBean.endTime;
            mOriginalEndTimeData = mTargetBean.endTime;
            mEndTime = new Date(mTargetBean.endTime);
            mAlertTimeText = mTargetBean.reminderText;
            String endTime = TimeUtils.timeFormatString(mEndTime);
            mEndTimeShow.setText(endTime);
            mAlertTimeShow.setText(mAlertTimeText);
            mColorCenter.setVisibility(View.VISIBLE);
            mColorCenter.setImageResource(mResourceId[mTargetBean.color - 1]);
            mColor1.setAlpha(0f);
            mColor2.setAlpha(0f);
            mColor3.setAlpha(0f);
            mColor4.setAlpha(0f);
            mColor5.setAlpha(0f);
            mColor6.setAlpha(0f);
            mType = mTargetBean.type;
            mTargetName.setText(mTargetBean.title);
            mNoteView.setText(mTargetBean.detail);
        }
    }

    private void initView() {
        mStartTimeView.setOnClickListener(this);
        mEndTimeView.setOnClickListener(this);
        mAlertTimeView.setOnClickListener(this);
        mStartTime = new Date();
        String startTime = TimeUtils.timeFormatString(mStartTime);
        mStartTimeShow.setText(startTime);
        mStartTimeData = mStartTime.getTime();
        mEndTime = new Date();
        String endTime = TimeUtils.timeFormatString(mEndTime);
        mEndTimeShow.setText(endTime);
        mEndTimeData = mEndTime.getTime();
        mColor1.setOnClickListener(this);
        mColor2.setOnClickListener(this);
        mColor3.setOnClickListener(this);
        mColor4.setOnClickListener(this);
        mColor5.setOnClickListener(this);
        mColor6.setOnClickListener(this);
        mSaveGoal.setOnClickListener(this);
        mCloseIcon.setOnClickListener(this);
        mColorCenter.setOnClickListener(this);
    }

    public static void startGoalDetailAddActivity(){
        Intent intent = new Intent(ApplicationHelper.getContext(), GoalDetailAddActivity.class);
        ApplicationHelper.getContext().startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.start_time:
                DatePickDialogHelper.showDatePickDialog(GoalDetailAddActivity.this, new OnSureLisener() {
                    @Override
                    public void onSure(Date date) {
                        mStartTime = date;
                        String startTime = TimeUtils.timeFormatString(mStartTime);
                        mStartTimeShow.setText(startTime);
                        mStartTimeData = mStartTime.getTime();
                    }
                });
                break;
            case R.id.schedule_end_time:
                DatePickDialogHelper.showDatePickDialog(GoalDetailAddActivity.this, new OnSureLisener() {
                    @Override
                    public void onSure(Date date) {
                        mEndTime = date;
                        String endTime = TimeUtils.timeFormatString(mEndTime);
                        mEndTimeShow.setText(endTime);
                        mEndTimeData = mEndTime.getTime();
                    }
                });
                break;
            case R.id.alert_time:
                DatePickDialogHelper.showDatePickDialog(GoalDetailAddActivity.this, new OnSureLisener() {
                    @Override
                    public void onSure(Date date) {
                        mAlertTime = date;
                        mAlertTimeText = TimeUtils.timeFormatString(mAlertTime.getTime());
                        mAlertTimeShow.setText(mAlertTimeText);
                        mAlertTimeData = mAlertTime.getTime();
                    }
                });
                break;
            case R.id.color_1:
            case R.id.color_2:
            case R.id.color_3:
            case R.id.color_4:
            case R.id.color_5:
            case R.id.color_6:
                startColorAnim(v.getId());
                break;
            case R.id.save_goal:
                mTitle = mTargetName.getText().toString();
                mNote = mNoteView.getText().toString();
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                String ymd = sf.format(mEndTimeData);
                ymd = ymd + " 23:59:59";
                String ymdStart = sf.format(mStartTimeData);
                ymdStart = ymdStart + " 00:00:00";
                try {
                    SimpleDateFormat sftest = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    mStartTimeData = sftest.parse(ymdStart).getTime();
                    mEndTimeData = sftest.parse(ymd).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if (isCreate) {
                    TargetObservable.saveTarget(mTitle, mStartTimeData, mEndTimeData, mNote, mType, mColor, mAlertTimeText, 0).registerObserver(new Observer<TargetBean, Integer, List<TargetBean>>() {
                        @Override
                        public void onFail(Integer integer) {
                            Log.e("ZXX", "fail save target");
                        }

                        @Override
                        public void onComplete(List<TargetBean> targetBeans) {
                            Log.e("ZXX","complete save target");
                        }

                        @Override
                        public void onSuccess(TargetBean targetBean) {
                            Log.e("ZXX","success save target");
                            Toast.makeText(GoalDetailAddActivity.this, "save successfully", Toast.LENGTH_SHORT).show();
                            if(mAlertTime != null){
                                AlarmManagerUtil.setGoalAlarm(GoalDetailAddActivity.this, 0, mAlertTimeData, (int)targetBean.id + 1000, 0, targetBean.title, 2, TimeUtils.getDayByTime(targetBean.startTime, targetBean.endTime));
                            }
                            finish();
                        }
                    }).startDataHandle();
                } else {
                    mTargetBean.title = mTitle;
                    mTargetBean.detail = mNote;
                    mTargetBean.startTime = mStartTimeData;
                    mTargetBean.endTime = mEndTimeData;
                    mTargetBean.type = mType;
                    mTargetBean.color = mColor;
                    mTargetBean.reminderText = mAlertTimeText;
                    if (mStartTimeData != mOriginalStartTimeData || mEndTimeData != mOriginalEndTimeData){
                        TargetDayObservable.queryTargetByTargetId(mTargetBean.id).registerObserver(new Observer<TargetDayBean, Integer, List<TargetDayBean>>() {
                            @Override
                            public void onFail(Integer integer) {

                            }

                            @Override
                            public void onComplete(List<TargetDayBean> targetDayBeen) {
                                if (targetDayBeen != null){
                                    TargetDayObservable.deleteTarget(targetDayBeen).startDataHandle();
                                }
                            }

                            @Override
                            public void onSuccess(TargetDayBean targetDayBean) {

                            }
                        }).startDataHandle();
                    }
                    TargetObservable.updateTarget(mTargetBean).registerObserver(new Observer<TargetBean, Integer, List<TargetBean>>() {
                        @Override
                        public void onFail(Integer integer) {

                        }

                        @Override
                        public void onComplete(List<TargetBean> targetBeen) {

                        }

                        @Override
                        public void onSuccess(TargetBean targetBean) {
                            if(mAlertTime != null){
                                AlarmManagerUtil.setGoalAlarm(GoalDetailAddActivity.this, 0, mAlertTimeData, (int)targetBean.id + 1000, 0, targetBean.title, 2, TimeUtils.getDayByTime(targetBean.startTime, targetBean.endTime));
                            }
                            finish();
                        }
                    }).startDataHandle();
                }
                break;
            case R.id.close:
                finish();
                break;
            case R.id.color_center:
                startAnimBack();
                break;
        }
    }

    private void startAnimBack() {
        mColorCenter.setVisibility(View.INVISIBLE);
        ObjectAnimator animator7 = ObjectAnimator.ofFloat(mColor1, "alpha", 0f, 1.0f);
        ObjectAnimator animator8 = ObjectAnimator.ofFloat(mColor2, "alpha", 0f, 1.0f);
        ObjectAnimator animator9 = ObjectAnimator.ofFloat(mColor3, "alpha", 0f, 1.0f);
        ObjectAnimator animator10 = ObjectAnimator.ofFloat(mColor4, "alpha", 0f, 1.0f);
        ObjectAnimator animator11 = ObjectAnimator.ofFloat(mColor5, "alpha", 0f, 1.0f);
        ObjectAnimator animator12 = ObjectAnimator.ofFloat(mColor6, "alpha", 0f, 1.0f);
        AnimatorSet set = new AnimatorSet();
        set.setDuration(500);
        set.playTogether(animator7,animator8,animator9,animator10,animator11,animator12);
        set.start();
    }

    private void startColorAnim(int id){
        switch(id){
            case R.id.color_1:
                mColorCenter.setImageResource(R.drawable.circle_shape_1);
                mColor = 1;
                break;
            case R.id.color_2:
                mColorCenter.setImageResource(R.drawable.circle_shape_2);
                mColor = 2;
                break;
            case R.id.color_3:
                mColorCenter.setImageResource(R.drawable.circle_shape_3);
                mColor = 3;
                break;
            case R.id.color_4:
                mColorCenter.setImageResource(R.drawable.circle_shape_4);
                mColor = 4;
                break;
            case R.id.color_5:
                mColorCenter.setImageResource(R.drawable.circle_shape_5);
                mColor = 5;
                break;
            case R.id.color_6:
                mColorCenter.setImageResource(R.drawable.circle_shape_6);
                mColor = 6;
                break;
        }
        ObjectAnimator animator7 = ObjectAnimator.ofFloat(mColor1, "alpha", 1.0f, 0f);
        ObjectAnimator animator8 = ObjectAnimator.ofFloat(mColor2, "alpha", 1.0f, 0f);
        ObjectAnimator animator9 = ObjectAnimator.ofFloat(mColor3, "alpha", 1.0f, 0f);
        ObjectAnimator animator10 = ObjectAnimator.ofFloat(mColor4, "alpha", 1.0f, 0f);
        ObjectAnimator animator11 = ObjectAnimator.ofFloat(mColor5, "alpha", 1.0f, 0f);
        ObjectAnimator animator12 = ObjectAnimator.ofFloat(mColor6, "alpha", 1.0f, 0f);
        AnimatorSet set = new AnimatorSet();
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                mColorCenter.setVisibility(View.VISIBLE);
                ObjectAnimator animator = ObjectAnimator.ofFloat(mColorCenter, "alpha", 0.7f, 1f);
                animator.setDuration(200);
                animator.start();
            }
        });
        set.setDuration(500);
        set.playTogether(animator7,animator8,animator9,animator10,animator11,animator12);
        set.start();
    }
}
